package yxy.game.pm2.command.hero;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Hero;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.module.hero.HeroHandle;

/** 武将 武将锁定 */
@MessageType(proto = Command.HeroLock, classtype = HeroMessage.HeroLockRequest.class)
public class CMD_HeroLock extends Command<HeroMessage.HeroLockRequest> {

	@Override
	public void execute(MessageSource messageSource, HeroMessage.HeroLockRequest request) {
		String playerCode = messageSource.getTag();
		String code = request.getCode();

		HeroMessage.HeroLockResponse.Builder response = HeroMessage.HeroLockResponse.newBuilder();

		try {
			if (Hero.lockHero(playerCode)) {
				HeroHandle heroHandle = new HeroHandle();
				Hero hero = heroHandle.getHero(playerCode, code);
				if (hero == null) {
					send(messageSource, response, Result.ParamError);
					return;
				}
				hero.setLock(!hero.isLock());
				heroHandle.updateHero(playerCode, hero);
				response.setCode(code);
				response.setLock(hero.isLock());
				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			Hero.unlockHero(playerCode);
		}
	}

	private void send(MessageSource messageSource, HeroMessage.HeroLockResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}